import { useState, useRef, useEffect } from 'react'
import styled from 'styled-components'

const Wrapper = styled.div`
  & canvas {
    margin-top: 3rem;
    border:1px solid blue;
  }
`

export default function Demo () {
  const refCanvas = useRef<any>(null)
  const [context, setContext] = useState<any>(null)

  useEffect(() => {
    const ctx = refCanvas.current?.getContext("2d");
    if (!!ctx) setContext(ctx);
  })

  const onDemo1 = () => {
    // 动态调整尺寸大小
    if (!refCanvas.current) return;
    refCanvas.current.width  = window.innerWidth  / 2;
    refCanvas.current.height = window.innerHeight / 2;
  }

  const onDemo2 = () => {
    // 基本图形：矩形, fill, clear, stroke
    // 基本样式：fillStyle
    // 坐标系：左上角（0，0）

    context.fillStyle = 'hsla(120, 75%, 50%, 1)'
    context.fillRect(50,50,100,70)

    context.fillStyle = 'hsla(0, 75%, 50%, 0.5)'
    context.fillRect(100,90,120,90)

    context.clearRect(160,120,40,40)
    context.strokeRect(10, 10, 220, 180);
  }

  const onDemo3 = () => {
    // 基本图形：路径, line
    // 基本样式：strokeStyle, lineWidth

    context.strokeStyle = 'red'
    context.lineWidth = 7;
    context.beginPath();
    context.moveTo(75, 50);
    context.lineTo(100, 75);
    context.lineTo(100, 25);
    context.closePath();
    context.stroke();
    context.fill();
  }

  const onDemo4 = () => {
    // 基本图形：路径, arc
    // 基本样式：strokeStyle, lineWidth

    context.strokeStyle = 'yellow'
    context.lineWidth = 3;
    
    context.beginPath();
    // face
    context.arc(75, 75, 50, 0, Math.PI * 2, true);
    // Mouth (clockwise)
    context.moveTo(110, 75);
    context.arc(75, 75, 35, 0, Math.PI, false);
    // Left eye
    context.moveTo(65, 65);
    context.arc(60, 65, 5, 0, Math.PI * 2, true);
    // Right eye
    context.moveTo(95, 65);
    context.arc(90, 65, 5, 0, Math.PI * 2, true);

    context.stroke();
  }

  const onMouseClick = (event:any) => {
    // DOM 事件坐标系 与 canvas 坐标系
    
    if (!refCanvas.current) return;
    const rect = refCanvas.current.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    console.log(rect.left, rect.top)
    console.log(event.clientX, event.clientY)
    console.log(x, y)

    context.strokeStyle = 'green'
    context.lineWidth = 3;
    context.beginPath();
    context.moveTo(x+5,y);
    context.arc(x,y,5,0,Math.PI * 2, true);
    context.stroke();
  }

  return (
    <Wrapper>
      <h1>Canvas Demo</h1>
      <div>
        <button onClick={!!context ? onDemo1 : undefined}>#1</button>
        <button onClick={!!context ? onDemo2 : undefined}>#2</button>
        <button onClick={!!context ? onDemo3 : undefined}>#3</button>
        <button onClick={!!context ? onDemo4 : undefined}>#4</button>
      </div>
      <canvas ref={refCanvas} onClick={onMouseClick} width="100" height="100">
        !!! This browser doesn't support canvas !!!
      </canvas>
    </Wrapper>
  )
}
